package com.example.springboot.controller.pdf;

import com.example.springboot.pojo.pdf.PdfEntity;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author:ChenZhangKun
 * @Date: 2021/11/23 10:20
 */
@Slf4j
@RestController
@RequestMapping("/czk/pdf")
@Api(tags = "pdf管理")
public class PdfController {
    @PostMapping("/down")
    public String exportPdf(@RequestBody PdfEntity pdfEntity, HttpServletResponse response) throws UnsupportedEncodingException {
        // 指定解析器
        System.setProperty("javax.xml.parsers.DocumentBuilderFactory",
                "com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl");
        String filename = "车辆维修审批单.pdf";
        String path = "D:/";
        response.setContentType("application/pdf");
        response.setHeader("Content-Disposition", "attachment;fileName="
                + URLEncoder.encode(filename, "UTF-8"));
        OutputStream os = null;
        PdfStamper ps = null;
        PdfReader reader = null;
        try {
            // 拿到输出流
            os = response.getOutputStream();
            // 读取pdf表单
            reader = new PdfReader(path+"/"+filename);
            // 3 根据表单生成一个新的pdf
            ps = new PdfStamper(reader, os);
            // 获取表单
            AcroFields form = reader.getAcroFields();
            // 给表单添加中文字体 这里采用系统字体。不设置的话，中文可能无法显示
            BaseFont bf = BaseFont.createFont("C:/WINDOWS/Fonts/SIMSUN.TTC,1",
                    BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            form.addSubstitutionFont(bf);
            Map<String, Object> data = new HashMap<>();
            data.put("time", pdfEntity.getTime());
            data.put("name", pdfEntity.getName());
            data.put("number", pdfEntity.getNumber());
            data.put("type", pdfEntity.getType());
            data.put("localtion", pdfEntity.getLocaltion());
            data.put("cost", pdfEntity.getCost());
            data.put("content", pdfEntity.getContent());
            data.forEach((key, value) -> {
                try {
                    // 由于pdf的补课编辑，这里没有用工具Adobe Acrobat DC准备为可编辑的表单，所以这里会报错为read-only
                    form.setField(key, value.toString());
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (DocumentException e) {
                    e.printStackTrace();
                }
            });
            ps.setFormFlattening(true);
            log.info("*******************PDF导出成功***********************");
            return "success";
        } catch (Exception e) {
            e.printStackTrace();
            log.info("*******************PDF导出失败***********************");
        } finally {
            try {
                ps.close();
                reader.close();
                os.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return "fail";
    }
}
